<?php
namespace app\api\controller;

/*个人中心控制器*/

use think\facade\Db;
use think\Request;
use app\BaseController;
use app\common\controller\ApiController;
use think\App;
use think\facade\Cache;

class User extends ApiController
{
    use \app\common\traits\Crypt;

    public function initialize()
    {
        parent::initialize();
        $this->wx_user = app('app\common\model\user\WxUsers');
        $this->sms_logs = app('app\common\model\system\SmsLogs');
        $this->configuration = app('app\common\model\system\Configuration');
        $this->wx_api = app('app\common\service\WxApi');
        $this->integral_detail = app('app\common\model\user\IntegralDetail');
        $this->chat_message = app('app\common\model\chat\ChatMessage');
        $this->system_admin = app('app\common\model\system\SystemAdmin');
        $this->address = app('app\common\model\user\Address');
    }

    //用户信息
    public function index(Request $request)
    {
        $info = $this->wx_user->find($request->user_id);
        $this->admin = app('app\common\model\system\SystemAdmin');
        $data['admin_id'] = 8;
        $data['user_id'] = $request->user_id;

        $data['admin_avatar_url'] = 'http://bgt-param.oss-cn-hangzhou.aliyuncs.com/upload/20200721/49640565c5f8400385e46403877181269a063d0a.png';
        $data['user_avatar'] = $this->wx_user->where('id' , $request->user_id)->value('avatar_url');
        $data['user_name'] = $this->wx_user->where('id' , $request->user_id)->value('nick_name');
        return json(['code' => 200 , 'msg' => '获取成功' , 'data' => ['info' => $info , 'data' => $data]]);
    }

    /**
     * 获取微信token
     * @param Request $request
     */
    public function token(Request $request)
    {

        $appid = $this->configuration->where('key' , 'wechat_app_id')->value('val');
        $appsecret = $this->configuration->where('key' , 'wechat_secret')->value('val');

        //$this->wx_api->getJssdkTicket($appid,$appsecret);//获取临时票据
        $data = $this->wx_api->getSignPackage($appid , $appsecret , $request->param('url'));//获取签名

        return json(['code' => 200 , 'msg' => '获取成功' , 'data' => [
            'data' => $data
        ]]);
    }

    //修改用户信息
    public function change_user_info(Request $request)
    {

        $data = $request->param('');

        $user = $this->wx_user->find($request->user_id);
        try {
            //验证验证码
            if ($request->param('phone')) {
                if (!$this->sms_logs->where(['mobile' => $request->param('phone') , 'code' => $request->param('code')])->find()) {

                    return json(['code' => 202 , 'msg' => '验证码错误']);
                };

                // Cookie::make("phone",$request->phone, time()+3600);
                if ($this->wx_user->where('phone' , $data['phone'])->find()) {
                    return json(['code' => 202 , 'msg' => '该手机号已注册']);
                }
                // dd($data);die;
                $key = $this->encrypt($request->param('phone'));
                $token = $key;
                $this->wx_user->where('id' , $request->user_id)->update(['api_token' => $token , 'key' => $key , 'phone' => $data['phone']]);
                Cache('Rmt_' . $request->param('phone') , $key , 36000000);
                //dd($user);
                //$user->update([]);
                //WxUsers::where('id',$request->user_id)->update($data);
                return json(['code' => 200 , 'msg' => '换绑成功' , 'data' => ['key' => $key]]);

            } elseif ($request->param('password')) { //修改密码

                $data['password'] = password($request->param('password'));

                $user->save($data);
            } elseif ($request->param('nick_name') != '') { //修改昵称
                if ($this->wx_user->where('nick_name' , $request->param('nick_name'))->find()) {
                    return json(['code' => 202 , 'msg' => '该昵称已存在']);
                }
                $user->save($data);
            } else {
                $user->save($data);

            }

            return json(['code' => 200 , 'msg' => '完善成功']);

        } catch ( \Exception $exception ) {
            return json(['code' => 202 , 'msg' => '完善失败' , 'data' => $exception->getMessage()]);
        }


    }

    //发送短信验证码
    public function send_code(Request $request)
    {

        try {
            $code = rand(100000 , 999999);
            $content = array(
                "code" => $code ,
            );//SMS_178500248
            $message = smsdemo($request->param('phone') , $content , 'SMS_196658772');

            $sms_log = $this->sms_logs->save([
                'mobile' => $request->param('phone') ,
                'code' => $code ,

            ]);
            //dd($message);
            return json(['code' => 200 , 'msg' => '发送成功']);
        } catch ( \Exception $exception ) {
            return json(['code' => 202 , 'msg' => '发送失败' , 'data' => $exception->getMessage()]);

        }

    }

    /**
     * Login Or Register
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function register(Request $request)
    {

        try {

            $post = $request->param('');

            $this->validate($post , [
                'phone' => 'required|unique:investor' ,
                'phone' => 'regex:/^1[345789][0-9]{9}$/' ,     //正则验证

            ]);
            if ($post['phone'] == '') {
                throw new \Exception("手机号不能为空");
            }
            //dump($this->sms_logs->where(['mobile'=>$post['phone'],'code'=>$post['code']])->find());
            //dd($this->sms_logs->getLastSql());

            //验证验证码
            if ($post['code'] && !$this->sms_logs->where(['mobile' => $post['phone'] , 'code' => $post['code']])->find()) {

                return json(['code' => 202 , 'msg' => '验证码错误']);
            };

            //判断是登入还是注册
            $user = $this->wx_user->where('phone' , $post['phone'])->find();

            if ($user) {

                //判断是否密码登陆
                if (isset( $post['password'] ) && $post['password'] != '') {
                    if (password($post['password']) != $user->password) {
                        return json(['code' => 202 , 'msg' => '密码错误']);
                    }
                }
                $key = $this->encrypt($user->phone);
                $token = $key;
                $user->save(['api_token' => $token , 'key' => $key]);
                Cache('Rmt_' . $post['phone'] , $key , 36000000);
                $data['admin_avatar_url'] = 'http://bgt-param.oss-cn-hangzhou.aliyuncs.com/upload/20200721/49640565c5f8400385e46403877181269a063d0a.png';
                $data['user_avatar'] = $this->wx_user->where('id' , $request->user_id)->value('avatar_url');
                $data['user_name'] = $this->wx_user->where('id' , $request->user_id)->value('nick_name');
                //平台客服分流
                $to_platform = $this->chat_message->where(['from_id' => $request->user_id , 'type' => 2])->find();
                if ($to_platform) {//如果之前有和平台聊天的记录，就继续和之前的客服聊天
                    $data['admin_id'] = $to_platform->to_id;
                } else { //如果没有就使用客服分流
                    //查询所有平台客服账号
                    /* $service_list = $this->system_admin
                         ->where(['is_service'=>1,'is_store'=>0,'is_app'=>1,'is_online'=>1])
                         ->field('id,reception_number')
                         ->select();*/
                    $service_list = $this->system_admin
                        ->where(['is_service' => 1 , 'is_store' => 0 , 'store_id' => 0 , 'is_app' => 1/*,'is_online'=>1*/])
                        ->field('id,reception_number')
                        ->select()->toArray();

                    $data['admin_id'] = $service_list[array_rand($service_list)]['id'];
                }

                $data['admin_avatar_url'] = 'http://bgt-param.oss-cn-hangzhou.aliyuncs.com/upload/20200721/49640565c5f8400385e46403877181269a063d0a.png';
                $data['user_id'] = $user->id;

                $data['user_avatar'] = $this->wx_user->where('id' , $user->id)->value('avatar_url');
                $data['user_name'] = $this->wx_user->where('id' , $user->id)->value('nick_name');

            } else {

                if ($post['password'] != '') {
                    return json(['code' => 202 , 'msg' => '手机号未注册']);
                }

                if (( $post['code'] == '' ) || ( $post['code'] && !$this->sms_logs->where(['mobile' => $post['phone'] , 'code' => $post['code']])->find() )) {

                    return json(['code' => 202 , 'msg' => '验证码错误']);
                };

                $key = $this->encrypt($request->param('phone'));
                $user = $this->wx_user->save(['avatar_url' => 'http://bgt-param.oss-cn-hangzhou.aliyuncs.com/2020-04-02_1585809316_5e8587a489302.png' , 'phone' => $post['phone'] ,
                    'api_token' => $key , 'key' => $key]);

                /*$token = $key;*/
                $this->wx_user->where('id' , $this->wx_user->id)->save(['nick_name' => '小潮' . $this->wx_user->id , 'name' => '小潮' . $this->wx_user->id]);

                Cache('Rmt_' . $post['phone'] , $key , 36000000);
                $data['admin_avatar_url'] = 'http://bgt-param.oss-cn-hangzhou.aliyuncs.com/upload/20200721/49640565c5f8400385e46403877181269a063d0a.png';
                /*$data['user_avatar'] = $this->wx_user->where('id', $request->user_id)->value('avatar_url');
                $data['user_name'] = $this->wx_user->where('id', $request->user_id)->value('nick_name');*/
                //平台客服分流
                $to_platform = $this->chat_message->where(['from_id' => $request->user_id , 'type' => 2])->find();
                if ($to_platform) {//如果之前有和平台聊天的记录，就继续和之前的客服聊天
                    $data['admin_id'] = $to_platform->to_id;
                } else { //如果没有就使用客服分流
                    //查询所有平台客服账号
                    /* $service_list = $this->system_admin
                         ->where(['is_service'=>1,'is_store'=>0,'is_app'=>1,'is_online'=>1])
                         ->field('id,reception_number')
                         ->select();*/
                    $service_list = $this->system_admin
                        ->where(['is_service' => 1 , 'is_store' => 0 , 'store_id' => 0 , 'is_app' => 1/*,'is_online'=>1*/])
                        ->field('id,reception_number')
                        ->select()->toArray();

                    $data['admin_id'] = $service_list[array_rand($service_list)]['id'];
                }
                $data['admin_avatar_url'] = 'http://bgt-param.oss-cn-hangzhou.aliyuncs.com/upload/20200721/49640565c5f8400385e46403877181269a063d0a.png';
                $data['user_id'] = $this->wx_user->id;

                $data['user_avatar'] = $this->wx_user->where('id' , $this->wx_user->id)->value('avatar_url');
                $data['user_name'] = $this->wx_user->where('id' , $this->wx_user->id)->value('nick_name');


                $this->integral_detail->save(['user_id' => $this->wx_user->id , 'description' => '注册送积分' , 'integral' => 100 , 'type' => 1]);
                $this->wx_user->where('id' , $this->wx_user->id)->inc('integral' , 100)->update();
            }

            //redis登陆态持久化

            // Cookie::make("phone",$request->phone, time()+3600);

            return json(['code' => 200 , 'msg' => '注册成功,直接登录' , 'data' => ['key' => $key , 'data' => $data]]);
        } catch ( \Exception $exception ) {
            return json(['code' => 202 , 'msg' => '注册失败' , 'data' => $exception->getMessage()]);

        }
    }

    /*问题解答*/
    public function question(Request $request)
    {
        $this->question = app('app\common\model\system\Question');
        $res = $this->question->order('create_time' , 'desc')->paginate($request->param('limit' , 10));
        $data = [
            'total' => $res->total() ,         // 总记录数
            'current_page' => $res->currentPage() ,   // 当前页码
            'per_page' => $res->listRows() ,      // 每页记录数
            'data' => $res->items()          // 分页数据
        ];
        $data['mobile'] = $this->configuration->withoutGlobalScope()->find(24)->val;
        return json(['code' => 200 , 'msg' => '获取成功' , 'data' => $data]);
    }

    /*用户登录协议
    type：1登录协议；2：隐私政策,3:支付协议 ;4:合同
    */
    public function login_text(Request $request)
    {
        if ($request->param('type') == 1) {
            $res = $this->configuration->withoutGlobalScope()->where('id' , 25)->value('val');
        } elseif ($request->param('type') == 2) {
            $res = $this->configuration->withoutGlobalScope()->where('id' , 27)->value('val');
        } elseif ($request->param('type') == 3) {
            $res = $this->configuration->withoutGlobalScope()->where('id' , 28)->value('val');
        } else {
            $res = $this->configuration->withoutGlobalScope()->where('id' , 131)->value('val');
        }

        return json(['code' => 200 , 'msg' => '获取成功' , 'data' => $res]);
    }

    /**
     * 新增地址/修改地址
     * @param Request $request
     * @return \think\response\Json
     */
    public function edit_address(Request $request)
    {
        $params = $request->param();
        try {
            Db::startTrans();
            $this->validate($params , [
                'username|用户姓名' => 'require' ,
                'phone|联系电话' => 'require|mobile' ,
                'key|用户登陆信息' => 'require' ,
                'city|市' => 'require' ,
                'districts|区' => 'require' ,
                'address|详细地址' => 'require' ,
                'is_default|默认' => 'require' ,
            ]);

            //如果设置为默认地址则其他地址全部修改为非默认
            $list = $this->address->where('user_id' , $request->user_id)->select();

            $params['user_id'] = $request->user_id;
            $list->isEmpty() ==false  && $list->update(['is_default'=>0]);
            if (isset( $params['id'] ) && !empty( $params['id'] )) { //修改
                $info = $this->address->find($params['id']);
                $info->save($params);
            } else {//新增
                $this->address->save($params);
            }

            Db::commit();
            return json(['code' => 200 , 'msg' => '成功']);

        } catch ( \Exception $e ) {
            Db::rollback();
            return json(['code' => 202 , 'msg' => $e->getMessage()]);

        }
    }

    /**
     * 地址详情
     * @param Request $request
     * @return \think\response\Json
     */
    public function address_detail(Request $request)
    {
        $params = $request->param();
        try {
            Db::startTrans();
            $this->validate($params , [
                'address_id|地址id' => 'require' ,
                'key|用户登陆信息' => 'require' ,
            ]);

            $order_info = $this->address
                ->where('id' , $params['address_id'])
                ->find();

            return json(['code' => 200 , 'msg' => '成功' , 'data' => ['data' => $order_info]]);

        } catch ( \Exception $e ) {

            return json(['code' => 202 , 'msg' => $e->getMessage()]);

        }
    }

    /**
     * 地址列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function address_list(Request $request)
    {
        $params = $request->param();
        try {

            $this->validate($params , [
                'key|用户登陆信息' => 'require' ,
            ]);

            $order_info = $this->address
              ->select();

            return json(['code' => 200 , 'msg' => '成功' , 'data' => ['data' => $order_info]]);

        } catch ( \Exception $e ) {

            return json(['code' => 202 , 'msg' => $e->getMessage()]);

        }
    }

}
